package com.yanqu.road.server.gameplayer.module.activity.hongxian;

import com.yanqu.road.dao.impl.activity.hongxian.HongXianUserDataDaoImpl;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.hongxian.HongXianMemory;
import com.yanqu.road.entity.activity.hongxian.HongXianReward;
import com.yanqu.road.entity.activity.hongxian.HongXianUserData;
import com.yanqu.road.entity.activity.hongxian.config.HongXianImageInfo;
import com.yanqu.road.entity.activity.hongxian.config.HongXianMemoryInfo;
import com.yanqu.road.entity.activity.hongxian.config.HongXianRewardInfo;
import com.yanqu.road.entity.activity.hongxian.config.HongXiuConfig;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.entity.log.hongxian.LogHongXianFate;
import com.yanqu.road.entity.log.hongxian.LogHongXianReward;
import com.yanqu.road.pb.activity.HongXianActivityProto;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.player.BagModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.manger.ServerLanguageMgr;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.hongxian.HongXianActivityMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.log.AutoLogMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.ConfigHelper;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.util.*;

/**
 * 红仙
 */
public class HongXianActivityModule extends GeneralModule {

    private HongXianUserData userData;

    private Random random = new Random();

    public HongXianActivityModule(GamePlayer player) {
        super(player);
    }

    @Override
    public boolean loadData() {
        ActivityInfo activityInfo = HongXianActivityMgr.getActivityInfo();
        if(ActivityMgr.activityInShowTime(activityInfo)) {
            userData = new HongXianUserDataDaoImpl().getHongXianUserData(activityInfo.getActivityId(), player.getUserId());
        }
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return true;
    }

    @Override
    public boolean saveData() {
        if(userData != null){
            if(userData.isInsertOption()){
                new HongXianUserDataDaoImpl().add(userData);
            } else if (userData.isUpdateOption()) {
                new HongXianUserDataDaoImpl().update(userData);
            }
        }
        return true;
    }

    @Override
    public void afterLogin() {
        activityReload();
    }

    public void activityReload() {
        if (!SystemOpenMgr.systemOpen(player, eSystemId.HongXian.getValue())) {
            return;
        }

        HongXiuConfig config = HongXianActivityMgr.getConfig();
        if(config == null || !ActivityMgr.activityInShowTime(config.getActivityInfo())){
            return;
        }

        syncConfig(config);

        initUserData(config);

        if(!resetOneDay()) {
            syncUserData(config);
        }
    }

    private void syncUserData(HongXiuConfig config) {
        if(userData != null){
            HongXianActivityProto.HongXianUserDataSyncMsg.Builder clientMsg = HongXianActivityProto.HongXianUserDataSyncMsg.newBuilder();
            HongXianActivityProto.HongXianUserTempData.Builder builder = buildUserBuilder();
            clientMsg.setUserData(builder);
            player.sendPacket(Protocol.U_HONG_XIAN_SYNC_USER_DATA, clientMsg);
        }
    }

    private HongXianActivityProto.HongXianUserTempData.Builder buildUserBuilder() {
        HongXianActivityProto.HongXianUserTempData.Builder builder = HongXianActivityProto.HongXianUserTempData.newBuilder();
        builder.setScore(userData.getScore());
        builder.setDrawTimes(userData.getDrawTimes());
        builder.setClient(userData.getClientAnim());
        for (Map.Entry<Integer, HongXianReward> entry : userData.getSelectReward().entrySet()) {
            HongXianReward reward = entry.getValue();
            HongXianActivityProto.HongXianRewardTemp.Builder rewardBuild = HongXianActivityProto.HongXianRewardTemp.newBuilder();
            rewardBuild.setId(reward.getId());
            rewardBuild.setSelect(reward.getSelect());
            rewardBuild.setVal(reward.getVal());
            rewardBuild.setTotal(reward.getTotal());
            rewardBuild.setLastSelect(reward.getLastSelect());
            for (Map.Entry<String, Integer> gotEntry : reward.getGot().entrySet()) {
                HongXianActivityProto.HongXianStringIntPairMapTemp.Builder pair = HongXianActivityProto.HongXianStringIntPairMapTemp.newBuilder();
                rewardBuild.addTongJi(pair.setId(gotEntry.getValue()).setReward(gotEntry.getKey()));
            }
            builder.addReward(rewardBuild);
        }

        for (Map.Entry<Integer, HongXianMemory> memoryEntry : userData.getPoolDrawProcess().entrySet()) {
            HongXianMemory memory = memoryEntry.getValue();
            HongXianActivityProto.HongXianMemoryTemp.Builder memoryBuilder = HongXianActivityProto.HongXianMemoryTemp.newBuilder();
            memoryBuilder.setId(memory.getId());
            memoryBuilder.setTimes(memory.getTimes());
            memoryBuilder.setBaoDi(memory.getMn());
            //暂时不下发
            builder.addMemory(memoryBuilder);
        }
        return builder;
    }

    private boolean resetOneDay() {
        return false;
    }

    private synchronized void initUserData(HongXiuConfig config) {
        // 系统未解锁
        if (!SystemOpenMgr.systemOpen(player, eSystemId.HongXian.getValue())) {
            return;
        }

        // 没有活动
        if (!ActivityMgr.activityInShowTime(config.getActivityInfo()) || HongXianActivityMgr.getConfig() == null) {
            return;
        }

        ActivityInfo activityInfo = config.getActivityInfo();

        // 已经有数据了
        if (userData != null && userData.getActivityId() == activityInfo.getActivityId()) {
            return;
        }

        HongXianUserData tmpUserData = new HongXianUserData();

        tmpUserData.setActivityId(activityInfo.getActivityId());
        tmpUserData.setUserId(getUserId());

        Map<Integer, HongXianReward> selectReward = new HashMap<>();

        for (HongXianRewardInfo rewardInfo : config.getRewardInfoList()) {
            HongXianReward reward = new HongXianReward();
            reward.setId(rewardInfo.getId());
            reward.setGot(new HashMap<>());
            selectReward.put(reward.getId(), reward);
        }
        tmpUserData.setSelectReward(selectReward);

        Map<Integer, HongXianMemory> poolDrawProcess = new HashMap<>();
        for (HongXianMemoryInfo memoryInfo : config.getMemoryInfoList()) {
            HongXianMemory memory = new HongXianMemory();
            memory.setId(memoryInfo.getId());
            if(null != memoryInfo.getLeastNumMap() && memoryInfo.getLeastNumMap().size() == 2){
                int result = random(random, memoryInfo.getLeastNumMap());
                memory.setLn(result);
            }

            if(null != memoryInfo.getSpecialNumMap() && memoryInfo.getSpecialNumMap().size() == 2){
                int result = random(random, memoryInfo.getSpecialNumMap());
                memory.setMn(result);
            }

            if(null != memoryInfo.getNormalNumMap() && memoryInfo.getNormalNumMap().size() == 2){
                int result = random(random, memoryInfo.getNormalNumMap());
                memory.setMn(result);
            }

            poolDrawProcess.put(memory.getId(), memory);
        }
        tmpUserData.setPoolDrawProcess(poolDrawProcess);


        tmpUserData.setInsertOption();
        userData = tmpUserData;
    }

    private int random(Random random, List<Integer> weightList) {
        int min = weightList.get(0);
        int max = weightList.get(1);
        int result = max;
        if(max > min){
            result = min + random.nextInt(max - min + 1);
        }
        return result;
    }

    private void syncConfig(HongXiuConfig config) {
        HongXianActivityProto.HongXianConfigDataSyncMsg.Builder clientMsg = HongXianActivityProto.HongXianConfigDataSyncMsg.newBuilder();

        for (HongXianMemoryInfo info : config.getMemoryInfoList()) {
            HongXianActivityProto.HongXianMemoryInfoTemp.Builder builder = HongXianActivityProto.HongXianMemoryInfoTemp.newBuilder();
            builder.setId(info.getId());
            builder.setName(ServerLanguageMgr.getContent(info.getName(), player.getLanguage()));
            builder.setMemoryLevel(info.getMemoryLevel());
            builder.setText(ServerLanguageMgr.getContent(info.getText(), player.getLanguage()));
            builder.setFristWeight(info.getFristWeight());
            builder.setSecondWeight(info.getSecondWeight());
            builder.setLeastNum(info.getLeastNum());
            builder.setSpecialNum(info.getSpecialNum());
            builder.setNormalNum(info.getNormalNum());
            builder.setScore(info.getScore());
            builder.setEffect(info.getEffect());
            clientMsg.addMemory(builder);
        }
        for (HongXianRewardInfo rewardInfo : config.getRewardInfoList()) {
            HongXianActivityProto.HongXianRewardInfoTemp.Builder builder = HongXianActivityProto.HongXianRewardInfoTemp.newBuilder();
            builder.setId(rewardInfo.getId());
            builder.setName(ServerLanguageMgr.getContent(rewardInfo.getName(), player.getLanguage()));
            builder.setType(rewardInfo.getType());
            builder.setAward(rewardInfo.getAward());
            builder.setLevel(rewardInfo.getLevel());
            builder.setNotice(rewardInfo.getNotice());
            clientMsg.addReward(builder);
        }

        for (HongXianImageInfo info : config.getImageInfoList()) {
            HongXianActivityProto.HongXianImageInfoTemp.Builder builder = HongXianActivityProto.HongXianImageInfoTemp.newBuilder();
            builder.setId(info.getId());
            builder.setImageId(info.getImageId());
            builder.setType(info.getType());
            clientMsg.addImage(builder);
        }

        player.sendPacket(Protocol.U_HONG_XIAN_SYNC_CONFIG, clientMsg);
    }

    /**
     *
     * @param rewardReq
     */
    public int setSelectReward(HongXianActivityProto.HongXianSetSelectRewardReq rewardReq) {

        if(userData == null){
            return GameErrorCode.E_SYSTEM_NO_OPEN;
        }

        HongXiuConfig config = HongXianActivityMgr.getConfig();


        for (HongXianActivityProto.HongXianSelectRewardTemp temp : rewardReq.getSelectList()) {
            int id = temp.getId();
            String reward = temp.getReward();

            if(id <= 0 || id > config.getRewardInfoList().size() - 1){
                return GameErrorCode.E_REQUEST_ARGUMENT_ERROR;
            }
            if(StringUtils.isNullOrEmpty(reward)){
                return GameErrorCode.E_REQUEST_ARGUMENT_ERROR;
            }

            //奖池配置是否存在
            HongXianRewardInfo hongXianRewardInfo = config.getHongXianRewardInfo(id);
            if(hongXianRewardInfo == null){
                return GameErrorCode.E_REQUEST_ARGUMENT_ERROR;
            }

            //奖励是否存在
            if(!hongXianRewardInfo.getAwardMap().containsKey(reward)){
                return GameErrorCode.E_REQUEST_ARGUMENT_ERROR;
            }

            //当前奖池是否未设置
            HongXianReward xianReward = userData.getSelectReward().get(id);
            if(xianReward == null){
                return GameErrorCode.E_GAME_ERROR;
            }

            if(hongXianRewardInfo.getType() != 1){
                return GameErrorCode.E_REQUEST_ARGUMENT_ERROR;
            }

            //自选，需要判断次数
            int limit = hongXianRewardInfo.getAwardMap().get(reward);
            int times = xianReward.getGot().getOrDefault(reward, 0);
            if(times >= limit){
                return GameErrorCode.E_HONG_XIAN_REWARD_SELECTED_MAX_LIMIT;
            }
            xianReward.setSelect(reward);
            xianReward.setLastSelect(reward);
            userData.setUpdateOption();
        }

        HongXianActivityProto.HongXianSetSelectRewardResp.Builder clientMsg = HongXianActivityProto.HongXianSetSelectRewardResp.newBuilder();
        clientMsg.setRet(0);
        clientMsg.setUserData(buildUserBuilder());
        player.sendPacket(Protocol.U_HONG_XIAN_SET_SELECT_REWARD, clientMsg);
        return 0;
    }

    /**
     * 回忆
     * @param type 操作类型
     */
    public int memoryDraw(int type) {
        int times = 1;
        if(type == 10){
            times = 10;
        }
        if(userData == null){
            return GameErrorCode.E_SYSTEM_NO_OPEN;
        }

        HongXiuConfig config = HongXianActivityMgr.getConfig();

        if(type == 10){
            if(userData.getDrawTimes() < config.getTEN_GACHA_AND_SKIP()){
                return GameErrorCode.E_HONG_XIAN_TEN_LIMIT;
            }
        }

        //判断自选的是否已设置
        for (HongXianRewardInfo rewardInfo : config.getRewardInfoList()) {
            if(rewardInfo.getType() == 1){
                HongXianReward reward = userData.getSelectReward().get(rewardInfo.getId());
                if(StringUtils.isNullOrEmpty(reward.getSelect())){
                    return GameErrorCode.E_HONG_XIAN_REWARD_NO_SELECTED;
                }
            }
        }


        //判断道具是否足够
        long userBagItemCount = player.getModule(BagModule.class).getUserBagItemCount(config.getDrawItemId());
        times = Math.min(times, (int)userBagItemCount);

        if(times <= 0){
            return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
        }

        //公告
        List<HongXianActivityProto.HongXianNoticeMsg> noticeList = new ArrayList<>();

        //清理过程计算变量
        clearTempVal(userData);

        //保底状态副本，防止异常造成脏数据
        HashMap<Integer, HongXianMemory> copyMemoryMap = copyHongXianMemoryHashMap(userData);

        boolean success = true;

        RandomHelper randomHelper = new RandomHelper();
        List<HongXianMemoryInfo> resultList = new ArrayList<>();
        int curTimes = 0;

        //起始臻id
        int zhenStartId = config.getRewardInfoList().size() + 1;

        for (int i = 0; i < times; i++) {

            HongXianMemoryInfo get = drawOne(userData, zhenStartId, config, copyMemoryMap, randomHelper);

            if(get == null){
                success = false;
                break;
            }

            curTimes++;
            resultList.add(get);

            //判断是否进度满了，停止抽奖
            boolean end = false;
            for (Map.Entry<Integer, HongXianReward> entry : userData.getSelectReward().entrySet()) {
                //自选的达到了
                if(entry.getValue().getCalVal() >= 1000 && !StringUtils.isNullOrEmpty(entry.getValue().getSelect())){
                    end = true;
                    break;
                }
            }
            if(end){
                break;
            }
        }

        if(curTimes <= 0){
            return GameErrorCode.E_GAME_ERROR;
        }

        if(!success){
            return GameErrorCode.E_GAME_ERROR;
        }

        //扣道具
        Property cost =  new Property();
        cost.addProperty(config.getDrawItemId(), BigInteger.valueOf(curTimes));
        if(!player.getModule(CurrencyModule.class).removeCurrency(cost, eLogMoneyType.HongXianActivity, eLogMoneyType.HongXianActivityDrawConsume)){
            return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
        }
        int addPerception = 0;

        //大奖
        //判断是否出现臻，如果有，只上传一个公告
        HongXianMemoryInfo zhenMemoryInfo = null;
        for (HongXianMemoryInfo info : resultList) {
            if(config.getNoticeSpecialList().contains(info.getId())){
                zhenMemoryInfo = info;
                break;
            }
        }
        Property zhenReward = new Property();

        Property reward = new Property();
        //判断是否有进度满了，拿奖励
        for (Map.Entry<Integer, HongXianReward> entry : userData.getSelectReward().entrySet()) {
            HongXianReward value = entry.getValue();
            if (value.getCalVal() >= 1000) {

                //满级的次数
                int manNum = value.getCalVal() / 1000;

                //拿奖励
                HongXianRewardInfo hongXianRewardInfo = config.getHongXianRewardInfo(value.getId());
                if(hongXianRewardInfo.getType() == 3) {
                    Property property = PropertyHelper.parseStringToProperty(hongXianRewardInfo.getAward());
                    property.rideProperty(manNum);
                    reward.addProperty(property);
                }else if(hongXianRewardInfo.getType() == 2){
                    //随机，没有次数限制
                    List<String> list = new ArrayList<>();
                    List<Integer> weightList = new ArrayList<>();
                    for (Map.Entry<String, Integer> integerEntry : hongXianRewardInfo.getAwardMap().entrySet()) {
                        list.add(integerEntry.getKey());
                        weightList.add(integerEntry.getValue());
                    }
                    if(weightList.size() == 0){
                        return GameErrorCode.E_GAME_ERROR;
                    }
                    for (int i = 0; i < manNum; i++) {
                        int byWeight = randomHelper.getSafeRandomIndexByWeight(weightList);
                        String rw = list.get(byWeight);
                        reward.addProperty(PropertyHelper.parseStringToProperty(rw));
                    }
                }else {
                    //自选
                    reward.addProperty(PropertyHelper.parseStringToProperty(value.getSelect()));
                    //次数是否到了，要情况自选
                    Integer now = value.getGot().getOrDefault(value.getSelect(), 0) + 1;
                    value.getGot().put(value.getSelect(), now);
                    String rw = value.getSelect();
                    Integer limit = hongXianRewardInfo.getAwardMap().getOrDefault(value.getSelect(), 0);
                    if(now >= limit){
                        value.setLastSelect("");
                    }
                    //直接清空，让玩家重选
                    value.setSelect("");

                    if(zhenMemoryInfo == null) {
                        HongXianActivityProto.HongXianNoticeMsg.Builder noticeBuilder = HongXianActivityProto.HongXianNoticeMsg.newBuilder();
                        noticeBuilder.setNickName(player.getUserInfo().getNickName());
                        noticeBuilder.setServerId(ConfigHelper.getLong("serverId"));
                        noticeBuilder.setTime(System.currentTimeMillis());
                        noticeBuilder.setType(0);
                        noticeBuilder.setReward(rw);
                        noticeBuilder.setParams(ServerLanguageMgr.getContent(hongXianRewardInfo.getName(), player.getLanguage()));
                        noticeList.add(noticeBuilder.build());
                    }else {
                        zhenReward.addProperty(PropertyHelper.parseStringToProperty(rw));
                    }

                    //自选奖励日志
                    AutoLogMgr.add(new LogHongXianReward(userData.getActivityId(), userData.getUserId(), value.getId(), rw));
                }

                //更新进度
                value.setVal(value.getCalVal() - 1000 * manNum);
                value.setTempVal(0);
                value.setTotal(value.getTotal() + manNum);

                addPerception++;
            }else {
                //更新进度
                value.setVal(value.getVal() + value.getTempVal());
                value.setTempVal(0);
            }
        }

        //积分
        long addScore = 0L;
        for (HongXianMemoryInfo memoryInfo : resultList) {
            addScore += memoryInfo.getScore();
        }
        reward.addProperty(config.getEXCHANGE_SCORE_ITEM_ID(), BigInteger.valueOf(addScore));

        player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.HongXianActivity, eLogMoneyType.HongXianActivityDrawReward);
        userData.setScore(addScore + userData.getScore());
        userData.setPerception(userData.getPerception() + addPerception);
        userData.setDrawTimes(userData.getDrawTimes() + curTimes);
        userData.setPoolDrawProcess(copyMemoryMap);
        //清除中间状态
        clearTempVal(userData);
        userData.setUpdateOption();
        player.notifyListener(eGamePlayerEventType.HongXianUserRank.getValue(), userData.getScore());
        player.notifyListener(eGamePlayerEventType.HongXianGanWuAchieve.getValue(), userData.getDrawTimes());

        HongXianActivityProto.HongXianDrawResp.Builder clientMsg = HongXianActivityProto.HongXianDrawResp.newBuilder();
        clientMsg.setRet(0);
        for (HongXianMemoryInfo memoryInfo : resultList) {
            clientMsg.addSuiPianId(memoryInfo.getId());
        }
        clientMsg.setReward(PropertyHelper.parsePropertyToString(reward));
        clientMsg.setTimes(curTimes);
        clientMsg.setUserData(buildUserBuilder());

        player.sendPacket(Protocol.U_HONG_XIAN_MEMORY_DRAW, clientMsg);

        if(zhenMemoryInfo != null){
            HongXianActivityProto.HongXianNoticeMsg.Builder noticeBuilder = HongXianActivityProto.HongXianNoticeMsg.newBuilder();
            noticeBuilder.setNickName(player.getUserInfo().getNickName());
            noticeBuilder.setServerId(ConfigHelper.getLong("serverId"));
            noticeBuilder.setTime(System.currentTimeMillis());
            noticeBuilder.setType(0);
            noticeBuilder.setReward(PropertyHelper.parsePropertyToString(zhenReward));
            noticeBuilder.setParams(ServerLanguageMgr.getContent(zhenMemoryInfo.getName(), player.getLanguage()));
            noticeList.add(noticeBuilder.build());
        }
        if(noticeList.size() > 0){
            HongXianActivityProto.HongXianUploadNoticeMsg.Builder uploadMsg = HongXianActivityProto.HongXianUploadNoticeMsg.newBuilder();
            uploadMsg.setActivityId(userData.getActivityId());
            uploadMsg.addAllNotice(noticeList);
            player.sendPacket(Protocol.C_HONG_XIAN_NOTICE_UPLOAD, uploadMsg);
        }

        //日志
        List<Integer> memIdList = new ArrayList<>();
        for (HongXianMemoryInfo info : resultList) {
            memIdList.add(info.getId());
        }
        LogHongXianFate logHongXianFate = new LogHongXianFate(userData.getActivityId(), userData.getUserId(), curTimes, addScore, userData.getScore(), StringUtils.listToString(memIdList, ","), memIdList);
        AutoLogMgr.add(logHongXianFate);

        return 0;
    }

    private HongXianMemoryInfo drawOne(HongXianUserData userData, int zhenStartId, HongXiuConfig config, HashMap<Integer, HongXianMemory> copyMemoryMap, RandomHelper randomHelper) {
        //防欧的臻
        List<HongXianMemoryInfo> excludeList = new ArrayList<>();

        HongXianMemoryInfo get = null;
        //臻是否达到保底
        for (HongXianMemoryInfo memoryInfo : config.getMemoryInfoList()) {
            if(memoryInfo.getId() < zhenStartId){
                continue;
            }
            HongXianMemory memory = copyMemoryMap.get(memoryInfo.getId());
            //防欧,未到
            if(memory.getLn() > 0 && memory.getTimes() < memory.getLn()){
                excludeList.add(memoryInfo);
                continue;
            }
            //是否到达保底
            if(memory.getMn() > 0 && memory.getTimes() + 1 >= memory.getMn()){
                get = memoryInfo;
                break;
            }
        }

        if(get == null){
            //普通是否保底
            for (HongXianMemoryInfo memoryInfo : config.getMemoryInfoList()) {
                if(memoryInfo.getId() >= zhenStartId){
                    continue;
                }
                HongXianMemory memory = copyMemoryMap.get(memoryInfo.getId());
                //是否到达保底
                if(memory.getMn() > 0 && memory.getTimes() + 1 >= memory.getMn()){
                    get = memoryInfo;
                    break;
                }
            }
        }

        if(get == null){
            List<Integer> weightOneList = new ArrayList<>();
            List<HongXianMemoryInfo> oneList = new ArrayList<>();
            //按概率来
            for (HongXianMemoryInfo memoryInfo : config.getMemoryInfoList()) {
                if(memoryInfo.getId() >= zhenStartId){
                    continue;
                }
                weightOneList.add(memoryInfo.getFristWeight());
                oneList.add(memoryInfo);
            }
            int index = randomHelper.getSafeRandomIndexByWeight(weightOneList);
            HongXianMemoryInfo first = oneList.get(index);
            HongXianMemoryInfo second = config.getHongXianMemoryInfoZhen(first.getId(), first.getMemoryLevel());
            if(second == null || excludeList.contains(second)){
                //没有二步配置
                get = first;
            }else {
                List<Integer> weightTwoList = new ArrayList<>();
                weightTwoList.add(first.getSecondWeight());
                weightTwoList.add(second.getSecondWeight());
                List<HongXianMemoryInfo> twoList = new ArrayList<>();
                twoList.add(first);
                twoList.add(second);
                index = randomHelper.getSafeRandomIndexByWeight(weightTwoList);
                get = twoList.get(index);
            }
        }

        if(get == null){
            return null;
        }

        if(get.getId() < zhenStartId){
            //重置普通保底
            HongXianMemory memory = copyMemoryMap.get(get.getId());
            memory.setTimes(0);
            HongXianMemoryInfo memoryInfo = config.getHongXianMemoryInfo(get.getId());
            if(memoryInfo.getNormalNumMap() != null) {
                memory.setMn(random(random, memoryInfo.getNormalNumMap()));
            }
            //日志

        }else if(get.getId() >= zhenStartId){

            //重置臻保底
            HongXianMemory memory = copyMemoryMap.get(get.getId());
            HongXianMemoryInfo memoryInfo = config.getHongXianMemoryInfo(get.getId());
            memory.setTimes(0);
            if(memoryInfo.getSpecialNumMap() != null) {
                memory.setMn(random(random, memoryInfo.getSpecialNumMap()));
            }
            if(memoryInfo.getLeastNumMap() != null) {
                memory.setLn(random(random, memoryInfo.getLeastNumMap()));
            }
            //日志

        }

        //累加进度和次数
        for (Map.Entry<Integer, HongXianMemory> entry : copyMemoryMap.entrySet()) {
            HongXianMemory value = entry.getValue();
            if(value.getId() == get.getId()){
                continue;
            }
            value.setTimes(value.getTimes() + 1);
        }
        HongXianMemoryInfo memoryInfo = config.getHongXianMemoryInfo(get.getId());
        for (int k = 1; k <= memoryInfo.getEffectMap().size(); k++) {
            Integer val = memoryInfo.getEffectMap().get(k - 1);
            HongXianReward reward = userData.getSelectReward().get(k);
            reward.setTempVal(reward.getTempVal() + val);
        }

        return get;
    }

    public int getUserDataMsg() {
        if(userData == null){
            return GameErrorCode.E_SYSTEM_NO_OPEN;
        }
        HongXianActivityProto.HongXianGetUserDataRespMsg.Builder builder = HongXianActivityProto.HongXianGetUserDataRespMsg.newBuilder();
        builder.setUserData(buildUserBuilder());
        player.sendPacket(Protocol.U_HONG_XIAN_GET_USER_DATA, builder.setRet(0));
        return 0;
    }

    private HashMap<Integer, HongXianMemory> copyHongXianMemoryHashMap(HongXianUserData userData) {
        HashMap<Integer, HongXianMemory> copyMemoryMap = new HashMap<>();
        for (Map.Entry<Integer, HongXianMemory> entry : userData.getPoolDrawProcess().entrySet()) {
            HongXianMemory value = entry.getValue();
            copyMemoryMap.put(entry.getKey(), value.clone());
        }
        return copyMemoryMap;
    }

    private void clearTempVal(HongXianUserData userData) {
        boolean change = false;
        for (Map.Entry<Integer, HongXianReward> rewardEntry : userData.getSelectReward().entrySet()) {
            HongXianReward reward = rewardEntry.getValue();
            if(reward.getTempVal() > 0){
                reward.setTempVal(0);
                change = true;
            }
        }
        if(change){
            userData.setUpdateOption();
        }
    }

    public HongXianUserData getUserData() {
        return userData;
    }
}
